package com.sinopec.uhf.initrc

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.sinopec.iuhf.IUhfHelper
import com.sinopec.uhf.uhfhelp.UhfHelp
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

//通过协程来读取 关闭协程 则读取就关闭
class LifecycleUhfHelper : LifecycleEventObserver, IUhfHelper {

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_CREATE -> {
                UhfHelp.initConnection()
            }

            Lifecycle.Event.ON_DESTROY -> {
                UhfHelp.closeConnection()
            }

            else -> {

            }
        }
    }

    override fun readTags(userOrEpc: (user: String, epc: String) -> String): Flow<String> {
        return CoroutineRead.readATag()
            .map {
                if (it == null) {
                    ""
                } else {
                    userOrEpc(it.strData ?: "", it.strEpc ?: "")
                }
            }
    }

}

//从生命周期中获取 uhf控制器 它会自动跟随生命周期的变化向uhf内核发送指令
val LifecycleOwner.lifecycleUhfHelper: LifecycleUhfHelper
    get() {
        val helper = LifecycleUhfHelper()
        lifecycle.addObserver(helper)
        return helper
    }